//
//  CXNavigationController.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/18.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

class CXNavigationController: UINavigationController, UIGestureRecognizerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //对导航栏的弹出进行判断 修复根控制器多次视图滑动pop而带来的无法push新控制器的问题
        interactivePopGestureRecognizer?.delegate = self
    }

    ///  由于tabBarController的子控制器是navigationController，因此一开始进入navigation的rootController时，会调用该方法。因此整个判断应该放在 childViewControllers是否大于零下
    override func pushViewController(viewController: UIViewController, animated: Bool) {
        //防止一进入根控制器就设置
        if childViewControllers.count > 0 {
            
            var leftTitle:String? = "返回"
            if childViewControllers.count == 1 {
                leftTitle = childViewControllers[0].navigationItem.title ?? "返回"
            }
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(imageNamed: "navigationbar_back_withtext", title: leftTitle, target: self, action: "pop")
        }
        super.pushViewController(viewController, animated: animated)
    }
    
    @objc private func pop() {
        popViewControllerAnimated(true)
    }
}

extension CXNavigationController {
    
    //实现代理方法
    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        if viewControllers.count == 1 {
            return false
        }
        return true
    }
}